package com.jwdf.uda.ui.fragment.user.login;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.databinding.FragmentLoginEntryBinding;
import com.jwdf.uda.event.ThirdPartEvent;
import com.jwdf.uda.event.UserEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.LoginAction;
import com.jwdf.uda.http.action.UpdateDeviceInfo;
import com.jwdf.uda.ui.activity.ForgetPasswordActivity;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.ui.fragment.user.bean.UserSession;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.ToastUtils;
import com.jwdf.uda.utils.UdaUtils;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/5/30.
 */
public class LoginEntryFragment extends BaseFragment {
    private static final int MSG_AUTH_COMPLETE = 1;
    private static final int MSG_AUTH_CANCEL = 2;
    private static final int MSG_AUTH_ERROR = 3;
    private FragmentLoginEntryBinding mDataBinding;
    private View.OnFocusChangeListener mInputFocusListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (R.id.input_edit_user_name == v.getId()) {
                if (!hasFocus) {
                    mDataBinding.ivClearUserNameInput.setVisibility(View.GONE);
                } else {
                    if (mDataBinding.inputEditUserName.getText().toString().length() > 0) {
                        mDataBinding.ivClearUserNameInput.setVisibility(View.VISIBLE);
                    }
                }
            } else if (R.id.input_edit_passwd == v.getId()) {
                if (!hasFocus) {
                    mDataBinding.ivClearPasswdInput.setVisibility(View.GONE);
                } else {
                    if (mDataBinding.inputEditPasswd.getText().toString().length() > 0) {
                        mDataBinding.ivClearPasswdInput.setVisibility(View.VISIBLE);
                    }
                }
            }
        }
    };
    private TextWatcher mUserTextChangeListener = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //mDataBinding.inputEditUserName.setSelection(s.length());
        }

        @Override
        public void afterTextChanged(Editable s) {
            mDataBinding.ivClearUserNameInput.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE);
        }
    };
    private TextWatcher mPassTextChangeListener = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //mDataBinding.inputEditPasswd.setSelection(s.length());
        }

        @Override
        public void afterTextChanged(Editable s) {
            mDataBinding.ivClearPasswdInput.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE);
        }
    };
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_AUTH_COMPLETE:
                    Bundle data = msg.getData();
                    String type = data.getString("type");
                    String openId = data.getString("openId");
                    String name = data.getString("name");
                    String pic = data.getString("pic");
                    ThirdPartEvent event = new ThirdPartEvent(ThirdPartEvent.EVENT_AUTH_COMPLETE);
                    event.loginType = type;
                    event.usrOpenId = openId;
                    event.usrName = name;
                    event.usrPic = pic;
                    EventBusUtil.post(event);
                    break;
                case MSG_AUTH_CANCEL:
                    closeProgressDialog();
                    break;
                case MSG_AUTH_ERROR:
                    closeProgressDialog();
                    Bundle data2 = msg.getData();
                    ToastUtils.show(getContext(), data2.getString("content"));
                    break;
            }
        }
    };
    public View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (R.id.btn_login == v.getId()) {
                UdaUtils.hideInputMethod(v.getContext(), v);
                mDataBinding.ivClearUserNameInput.setVisibility(View.GONE);
                mDataBinding.ivClearPasswdInput.setVisibility(View.GONE);
                String usrName = mDataBinding.inputEditUserName.getText().toString().trim();
                String passwd = mDataBinding.inputEditPasswd.getText().toString().trim();
                if (TextUtils.isEmpty(usrName)) {
                    ToastUtils.show(getContext(), getString(R.string.user_can_not_be_null));
                    return;
                }
                if (TextUtils.isEmpty(passwd)) {
                    ToastUtils.show(getContext(), getString(R.string.pwd_can_not_be_null));
                    return;
                }
                login(usrName, passwd);
            } else if (R.id.tv_forget_passwd == v.getId()) {
//                startActivityFromFragment(ForgetPasswordActivity.class);
                ForgetPasswordActivity.start(getContext(), "1");
            } else if (R.id.ll_wechat_login == v.getId()) {
                thirdPartyLogin(Wechat.NAME);
            } else if (R.id.ll_weibo_login == v.getId()) {
                thirdPartyLogin(SinaWeibo.NAME);
            } else if (R.id.ll_qq_login == v.getId()) {
                thirdPartyLogin(QQ.NAME);
            } else if (R.id.iv_clear_user_name_input == v.getId()) {
                mDataBinding.inputEditUserName.setText("");
            } else if (R.id.iv_clear_passwd_input == v.getId()) {
                mDataBinding.inputEditPasswd.setText("");
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mDataBinding = FragmentLoginEntryBinding.inflate(inflater, container, false);
        mDataBinding.setLoginEntryFragment(this);
        initViews();
        return mDataBinding.getRoot();
    }

    //    @Override
//    public void onResume() {
//        super.onResume();
//        closeProgressDialog();
//    }
    private void initViews() {
        mDataBinding.inputEditUserName.setText(getArguments().getString("mobile", ""));
        mDataBinding.inputEditUserName.addTextChangedListener(mUserTextChangeListener);
        mDataBinding.inputEditPasswd.addTextChangedListener(mPassTextChangeListener);
        mDataBinding.ivClearUserNameInput.setOnClickListener(mClickListener);
        mDataBinding.ivClearPasswdInput.setOnClickListener(mClickListener);
        mDataBinding.inputEditUserName.setOnFocusChangeListener(mInputFocusListener);
        mDataBinding.inputEditPasswd.setOnFocusChangeListener(mInputFocusListener);
        mDataBinding.inputEditUserName.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                return UdaUtils.filterEmoji(source.toString());
            }
        }});
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBusUtil.registerEvent(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBusUtil.unregisterEvent(this);
    }

    public void onEvent(ThirdPartEvent event) {
        if (ThirdPartEvent.EVENT_CLOSE_PROGRESS == event.getEvent()) {
            closeProgressDialog();
        }
    }

    private void login(String usrName, String passwd) {
        showProgressDialog();
        onNewRequestCall(LoginAction.newInstance(getContext(), usrName, passwd).request(new AHttpService.IResCallback<PbBean.PbResUserLogin>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserLogin> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
                    if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                        closeProgressDialog();
                        return;
                    }
                    PbBean.PbResUserLogin userLogin = response.body();
                    if (userLogin != null) {
                        UserSession userSession = new UserSession(userLogin.getSessionId(), userLogin.getToken());
                        userSession.setUserId(userLogin.getUserInfo().getUserId());
                        userSession.setStylist(userLogin.getUserInfo().getIsDesigner());
                        userSession.setUCoin(userLogin.getUserInfo().getMoney());
                        userSession.setUserName(userLogin.getUserInfo().getUsername());
                        ConfigUtils.setCurrentUser(getContext(), userSession);
                        if (!ConfigUtils.isRejectPrivacyPermission(getContext())) {
                            reportDeviceInfo(getContext());
                        } else {
                            closeProgressDialog();
                            UserEvent event = new UserEvent();
                            event.setEvent(UserEvent.EVENT_LOGIN);
                            EventBusUtil.post(event);
                        }
                    }
                }
            }
        }));
    }

    private void reportDeviceInfo(final Context context) {
        PushAgent.getInstance(context).enable(new IUmengRegisterCallback() {
            @Override
            public void onRegistered(final String deviceToken) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        onNewRequestCall(UpdateDeviceInfo.newInstance(context, deviceToken).request(new AHttpService.IResCallback<PbBean.PbResSystemUpdateDeviceInfo>() {
                            @Override
                            public void onCallback(int resultCode, Response<PbBean.PbResSystemUpdateDeviceInfo> response, PbBean.PbBaseServerInfo
                                    baseServerInfo) {
                                closeProgressDialog();
                                if (response != null) {
                                    if (HttpHelper.showError(context, resultCode, baseServerInfo, getString(R.string.error_net))) {
                                    }
                                    PbBean.PbResSystemUpdateDeviceInfo deviceInfo = response.body();
                                    if (deviceInfo != null) {
                                        ConfigUtils.setPageLength(context, deviceInfo.getPageLength());
                                        ConfigUtils.setAboutPage(context, deviceInfo.getAboutPage());
                                        ConfigUtils.setUserProtocol(context, deviceInfo.getUserProtocolPage());
                                    }
                                }
                                UserEvent event = new UserEvent();
                                event.setEvent(UserEvent.EVENT_LOGIN);
                                EventBusUtil.post(event);
                            }
                        }));
                    }
                });
            }
        });
    }

    private void thirdPartyLogin(final String typeName) {
        showProgressDialog();
        Platform platform = ShareSDK.getPlatform(getContext(), typeName);
        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Message msg = new Message();
                msg.what = MSG_AUTH_COMPLETE;
                Bundle bundle = new Bundle();
                bundle.putString("type", typeName);
                bundle.putString("openId", platform.getDb().getUserId());
                bundle.putString("name", platform.getDb().getUserName());
                bundle.putString("pic", platform.getDb().getUserIcon());
                msg.setData(bundle);
                mHandler.sendMessage(msg);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Message msg = new Message();
                msg.what = MSG_AUTH_ERROR;
                Bundle bundle = new Bundle();
                if (typeName.equals(Wechat.NAME)) {
                    bundle.putString("content", "请确认手机已经安装最新版本微信客户端");
                } else if (typeName.equals(SinaWeibo.NAME)) {
                    bundle.putString("content", "新浪微博登录失败");
                } else {
                    bundle.putString("content", "QQ登录失败");
                }

                msg.setData(bundle);
                mHandler.sendMessage(msg);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                mHandler.sendEmptyMessage(MSG_AUTH_CANCEL);
            }
        });
        platform.SSOSetting(false);
        platform.showUser(null);
    }
}
